package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private UserService userService;


    //发送短信验证码
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String, String> map) {
        //1.接收参数
        String phone = map.get("phone");

        //2.生成验证码,将验证码保存到session中
        //todo 写死一个验证码666 为了测试方便
        String code = "666";
        httpSession.setAttribute("SMS_" + phone, code);
        // smsTemplate.sendSms(phone, code);
        return ResultInfo.success(null);
    }

    //登录注册
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //1.接收参数phone,code
        String phone = map.get("phone");
        String code = map.get("code");
        //2.比对code 前端传递的和session中保存的不一致返回错误提示
        String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
        if (!StringUtils.equals(code, codeFromSession)
                || StringUtils.isEmpty(code)
                || StringUtils.isEmpty(codeFromSession)) {
            return ResultInfo.error("验证码不对");
        }
        //3.根据phone在数据库中查询
        User user = userService.findByPhone(phone);
        if (user != null) {

        } else {
            //如果没有查到,代表是新用户注册
            //将用户信息保存到user表中
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //4.将user信息保存到session中
        httpSession.setAttribute("SESSION_USER", user);
        //5.返回成功标识
        return ResultInfo.success(user);
    }

    //退出登录
    @PostMapping("/user/logout")
    public ResultInfo logout() {
        //将user信息从session中销毁
        httpSession.removeAttribute("SESSION_USER");
        return ResultInfo.success(null);

    }
}
